package com.lsht.common.word;

import cn.hutool.core.img.ImgUtil;
import lombok.SneakyThrows;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.rendering.ImageType;
import org.apache.pdfbox.rendering.PDFRenderer;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.awt.image.RenderedImage;
import java.io.File;

/**
 * @ClassName: CapturePdfFirstPageUtil
 * @Description: 获取pdf第一页当缩略图
 * @Author: zyc
 * @Date: 2023/10/12
 **/
public class CapturePdfFirstPageUtil {

    public static void generateBookIamge(File inputFile, File outputFile) {

        try {
            PDDocument document = PDDocument.load(inputFile);
            PDFRenderer pdfRenderer = new PDFRenderer(document);
            // 提取的页码
            int pageNumber = 0;
            // 以300 dpi 读取存入 BufferedImage 对象
            int dpi = 300;
            RenderedImage buffImage = pdfRenderer.renderImageWithDPI(pageNumber, dpi, ImageType.RGB);
            ImageIO.write(buffImage, "png", outputFile);
            document.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @SneakyThrows
    public static void getImage(String inputpdfPath, String outputjpgPath) {
        CapturePdfFirstPageUtil.generateBookIamge(new File(inputpdfPath), new File(outputjpgPath));
        BufferedImage bufferedImage = ImgUtil.toBufferedImage(ImageIO.read(new File(outputjpgPath)));
        int height = bufferedImage.getHeight();
        int width = bufferedImage.getWidth();
        System.out.println(height);
        System.out.println(width);
        ImgUtil.cut(new File(outputjpgPath), new File(outputjpgPath), new Rectangle(0, 300, width, new Double(height * 2 / 2).intValue()));
        ImgUtil.scale(new File(outputjpgPath), new File(outputjpgPath), 0.5f);
    }


    public static void main(String[] args) {
        CapturePdfFirstPageUtil.getImage("C:\\Users\\zyc18\\Desktop\\资料\\全域操作手册\\全域感知智能管理平台V1.0（管理端）-操作手册.pdf", "C:\\Users\\zyc18\\Desktop\\资料\\全域操作手册\\全域感知智能管理平台V1.0（管理端）-操作手册.jpg");

    }


}
